<template>
  <BreadCrumb>
    <template #default>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ name: 'ContentArticleList' }">文章管理</el-breadcrumb-item>
        <el-breadcrumb-item>新增文章</el-breadcrumb-item>
      </el-breadcrumb>
    </template>
  </BreadCrumb>
  <PageListContainer class="base-block article-list">
    <k-form ref="formRef" v-loading="contentLoading" :model="state.model" :rules="rules" label-width="90px">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="state.model.title" clearable placeholder="请填写文章标题" style="width: 60%" maxlength="20" />
      </el-form-item>
      <el-form-item label="文章类型" prop="article_type">
        <el-select v-model="state.model.article_type" placeholder="请选择文章类型" style="width: 320px">
          <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="文章作者" prop="author">
        <el-input v-model="state.model.author" clearable placeholder="请填写文章作者" style="width: 320px" maxlength="20" />
      </el-form-item>
      <el-form-item label="上传封面" prop="cover">
        <KImageUploader ref="uploadRef" :file-list="fileList" :limit="1" :on-before-upload="onBeforeUpload">
          <template #tip> 建议尺寸200*133，200KB以内，支持jpg/jpeg/png格式 </template>
        </KImageUploader>
      </el-form-item>
      <el-form-item label="定时发布" prop="publish_time">
        <el-date-picker
          v-model="state.model.publish_time"
          :shortcuts="dateShortcuts"
          type="datetime"
          format="YYYY-MM-DD HH:mm:ss"
          style="width: 320px"
          class="mr-10"
        />*非必填项，若填写时间，则为定时发布时间
      </el-form-item>
      <el-form-item label="摘要设置" prop="abstract">
        <el-input
          v-model="state.model.abstract"
          maxlength="80"
          allow-clear
          placeholder="请填写摘要"
          show-word-limit
          style="width: 60%"
          type="textarea"
          rows="4"
        />
      </el-form-item>
      <el-form-item label="文章内容" prop="article_content">
        <ContentEditor v-if="props.type !== 'check'" v-model:html="state.model.article_content" />
        <div v-else class="article-content" v-html="state.model.article_content"></div>
      </el-form-item>
      <el-form-item label-width="86px">
        <el-button v-if="props.type === 'edit' && props.id > 0" @click="onClickPreview">预览</el-button>
        <el-button :disabled="loading" @click="onReset">清空</el-button>
        <el-button :loading="loading" type="primary" @click="methods.onSubmit">发布</el-button>
      </el-form-item>
    </k-form>
  </PageListContainer>
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import { ref, watch, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { KImageUploader } from '@/components/k-image-uploader';
import { useForm } from '@crud/index';

import { toolReplaceEditorInput, isEmpty, toolGetSingleDateShortCuts as dateShortcuts } from '@/utils';
import configs from '@/config';

import { add, edit, getDetail } from '@/api/crm-content/article';
import ContentEditor from '@/components/base-editor/index.vue';
import BreadCrumb from '@/components/base-bread-crumb/index.vue';
defineOptions({ name: 'DyjNoticeAdd' });
const route = useRoute();
const router = useRouter();
const props = route.query as Record<string, any>;
const contentLoading = ref(false);
// options
const typeOptions = [
  {
    label: '行业资讯',
    value: 1
  },
  { label: '产品新知', value: 2 }
];
// 图片上传
const uploadRef = ref();
/** 默认图片 */
const fileList = ref<Record<string, any>[]>([]);
const formRef = ref();
// 判断富文本编辑器输入是否为空或回车
const validateContent = (rule: any, value: any, callback: any) => {
  const val = toolReplaceEditorInput(value);
  if (isEmpty(val)) {
    callback(new Error('请填写公告内容'));
  } else if (val.length < 5) {
    callback(new Error('公告内容不能少于5个字符'));
  // } else if (val.length > 10000) {
  //   callback(new Error('公告内容不能超过10000个字符'));
  } else {
    callback();
  }
};
const loading = ref(false);
const rules = {
  title: [{ required: true, message: '请填写文章标题' }],
  article_type: [{ required: true, message: '请选择文章类型' }],
  author: [{ required: true, message: '请填写文章作者' }],
  cover: [{ required: true, message: '请先上传封面', trigger: ['blur', 'change'] }],
  abstract: [{ required: true, message: '请填写摘要' }],
  article_content: [{ required: true, validator: validateContent }]
};
const { state, ...methods } = useForm({
  formRef,
  model: {
    title: '',
    article_type: 1,
    send_object: 0,
    publish_time: undefined,
    article_content: '',
    cover: undefined
  },
  onSubmit: async (model: any, mode = 0) => {
    let validate = false;
    if (formRef?.value?.validate) {
      validate = await formRef.value.validate();
    }
    if (!validate) return;
    loading.value = true;
    const publish_time = dayjs(model.publish_time).unix().valueOf();
    if (props.type === 'create') {
      const res = await add({ ...model, publish_time });
      loading.value = false;
      if (res.err) return;
      ElMessage.success('发布成功');
      router.push({ name: 'ContentArticleList' });
    } else if (props.type === 'edit') {
      if (!props.id) return;
      const res = await edit({ ...model, id: props.id, publish_time, cover: model?.cover?.url ? model.cover.url : model.cover });
      loading.value = false;
      if (res.err) return;
      ElMessage.success('编辑成功');
      router.push({ name: 'ContentArticleList' });
    }
  }
});
// 图片上传
const onBeforeUpload = (file: any) => {
  const { size } = file;
  if (size > 200 * 1024) {
    ElMessage.error('文件需小于200kb');
    return false;
  }
  return true;
};
// 跳转到考古加预览接口
const onClickPreview = async () => {
  await methods.onSubmit();
  const url = `${configs.kgjDomain}/information/articleDetail/${props.id}?isPreview=true`;
  window.open(url, '_blank');
};
// 清空
const onReset = () => {
  methods.resetModel;
  fileList.value = [];
};
// 获取详情
const getDetailInfo = async () => {
  contentLoading.value = true;
  const res = await getDetail(props.id);
  contentLoading.value = false;
  const { data } = res;
  if (data) {
    state.model = {
      ...state.model,
      ...data,
      publish_time: data.publish_time * 1000,
      cover: data?.cover?.url ? data.cover.url : data.cover
    };
    fileList.value = data?.cover
      ? [
        {
          uid: -1,
          name: data.cover,
          url: data.cover
        }
      ]
      : [];
  }
};
// 编辑
if (props.type === 'edit' || props.type === 'check') {
  getDetailInfo();
}
watch(
  () => uploadRef?.value?.getImgUrl(),
  (val) => {
    const imageUrl = state.model.cover;
    state.model.cover = val;
    nextTick(() => {
      if (val || (val !== imageUrl && val === undefined)) formRef?.value.validateField('cover');
    });
  },
  {
    immediate: false
  }
);
</script>
<style lang="scss" scoped>
.article-content {
  width: 80%;
  min-height: 300px;
  padding: 20px;
  word-break: break-all;
  white-space: pre-wrap;
  border: solid 1px #ccc;
}

.mr-10 {
  margin-right: 10px;
}
</style>
